"use strict"
var path = require('path');
var express = require('express')
var debug = require('debug')('app')
var bodyParser = require('body-parser')
var redis = require("redis");
var redis_host = process.env['REDIS_HOST'];
var redis_port = process.env['REDIS_PORT'];
var Weibo = require('./Weibo.js');
var WeiboManager = require('./WeiboManager.js');
var weiboSdk = require('nodeweibo');
weiboSdk.init(require('./setting.json'));
var redis_client = redis.createClient(redis_port, redis_host);
redis_client.on("error", function(err) {
    //console.log("Error " + err);
});
redis_client.on("subscribe", function(channel, count) {
    console.log("监听：" + channel);
});

const app = express()
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use('/static', express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))

redis_client.on("message", function(channel, message) {
    debug('收到消息：' + message);
    sendMsgToRooms(message);
});
redis_client.subscribe("pub_newsflash");

app.get('/', (req, res) => {
    res.render('dashboard', {
    	weibos : WeiboManager.getWeibos()
    });
});
app.get('/add-bot', (req, res) => {
   // weiboSdk.authorize();
    var redirectUrl = 'https://api.weibo.com/oauth2/authorize' + weiboSdk.getGetURL();
    res.redirect(redirectUrl);
});
app.post('/api/send-msg', (req, res) => {
    var msg = req.body.msg;
    if(msg[0]=='{'){
        msg = JSON.parse(msg).message;
    }
    var status  = {
        status:msg
    };
    WeiboManager.getWeibos().forEach((weibo)=>{
        weibo.uploadStatuses(status);
    })
    res.send({result:0});
})

app.post('/api/send-img-msg', (req, res) => {
    req.body.imgUrl
    var status  = {
        url:req.body.imgUrl,
        status :req.body.msg || '发布图片'
    };
    console.log(status);
    WeiboManager.getWeibos().forEach((weibo)=>{
        weibo.uploadImgStatuses(status);
    })
    res.send({result:0});
})

app.get('/oauth-callback', (req, res) => {
    var code = req.query.code;
    if (!code) {
        return res.redirect('/');
    }
    var jsonParas = {
        code: code,
        grant_type: "authorization_code"
    };
    weiboSdk.OAuth2.access_token(jsonParas, function(data) {
    	var time = (new Date).getTime();
    	data.expire_at = time+ data.expires_in * 1000;
        var weibo = new Weibo(data);
        WeiboManager.save(weibo);
        return res.redirect('/');
    });
});
const server = app.listen(3001)
